package com.lq.ecoldchain.util

import com.lq.ecoldchain.entity.QiNiuToken
import com.lq.ecoldchain.internet.BaseObserver
import com.qiniu.android.storage.*
import org.json.JSONException


/*
*2018/12/27 0027  15:55
*function by lq
*/
object QiNiuUtils {
    private var uploadManager: UploadManager

    init {
        val config = Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                .build()
        uploadManager = UploadManager(config)
    }


    interface OnQiNiuListener {
       fun uploadSuccess(url:String)
    }

    fun upload(path:String,listener:OnQiNiuListener) {
        BaseNetCore.ApiServiceImpl.getUpToken().compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<QiNiuToken>() {
            override fun onSuccess(t: QiNiuToken?) {
                val domain = t!!.domain
                uploadManager.put(path, null, t.upToken,{ _, info, response ->
                            if (info.isOK) {
                                toast { "上传成功" }
                                try {
                                    listener.uploadSuccess(domain+"/"+response.getString("key"))
                                }catch (e:JSONException){
                                }
                            } else {
                                toast { "上传失败" }
                            }
                        }, null)
            }
            override fun onFail(code: String) {
                logw { code }
            }
        })
    }
}